import router from './routerPc/index'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, setToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'
import useUserStore from '@/store/modules/user'
import usePermissionStore from '@/store/modules/permission'

NProgress.configure({ showSpinner: false })

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    setToken(getToken())
    // 判断当前用户是否已拉取完user_info信息
    if (!useUserStore().user) {
      isRelogin.show = true
      useUserStore().getInfo().then(() => {
        isRelogin.show = false
        next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
      }).catch(err => {
        useUserStore().logOut().then(() => {
          ElMessage.error(err)
          next({ path: '/' })
        })
      })
    } else {
      next()
    }
  } else {
    // 没有token
    next()
  }
})

router.afterEach((to) => {
  usePermissionStore().setCurrRoute(to.path)
  NProgress.done()
})
